import socket
import os
import sys

PORT = 8080
BUF_SIZE = 4096


def send_ota_file(client_sock, filename):
    print(f"[INFO] 客户端请求OTA文件: {filename}")
    try:
        # 检查文件是否存在
        if not os.path.exists(filename):
            not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"
            client_sock.sendall(not_found.encode())
            return

        # 获取文件大小
        filesize = os.path.getsize(filename)

        # 构建HTTP响应头
        header = (
            f"HTTP/1.1 200 OK\r\n"
            f"Content-Type: application/octet-stream\r\n"
            f"Content-Length: {filesize}\r\n"
            f"Content-Disposition: attachment; filename=\"ota.bin\"\r\n"
            f"Connection: close\r\n\r\n"
        )
        client_sock.sendall(header.encode())

        # 发送文件内容
        total = 0
        with open(filename, 'rb') as fp:
            while True:
                buf = fp.read(BUF_SIZE)
                if not buf:
                    break
                client_sock.sendall(buf)
                total += len(buf)
        print(f"[INFO] 已发送OTA文件，总字节数: {total}")
    except Exception as e:
        print(f"[ERROR] 发送OTA文件时出错: {e}")


def main():
    try:
        # 创建socket
        server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print(f"[INFO] Socket创建成功, fd={server_sock.fileno()}")

        # 设置地址复用
        server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # 绑定地址
        addr = ('', PORT)
        server_sock.bind(addr)
        print(f"[INFO] 绑定端口 {PORT} 成功")

        # 监听连接
        server_sock.listen(5)
        print(f"OTA HTTP服务器已启动，端口{PORT}")

        while True:
            print("[INFO] 等待客户端连接...")
            client_sock, client_addr = server_sock.accept()
            print(f"[INFO] 客户端已连接，地址={client_addr}, fd={client_sock.fileno()}")

            try:
                # 接收请求
                buffer = client_sock.recv(1024).decode('utf-8', errors='ignore')
                if buffer:
                    print(f"[INFO] 收到请求:\n{buffer}")
                    # 检查请求路径
                    if 'GET /bin/ota.bin' in buffer or 'GET //bin/ota.bin' in buffer:
                        send_ota_file(client_sock, 'bin/ota.bin')
                    else:
                        print("[WARN] 未知请求，返回404")
                        not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"
                        client_sock.sendall(not_found.encode())
                else:
                    print("[WARN] 未收到有效请求")
            except Exception as e:
                print(f"[ERROR] 处理客户端请求时出错: {e}")
            finally:
                # 关闭客户端连接
                client_sock.close()
                print("[INFO] 客户端连接已关闭")
    except Exception as e:
        print(f"[ERROR] 服务器异常: {e}")
    finally:
        if 'server_sock' in locals():
            server_sock.close()


if __name__ == '__main__':
    main()